package git.soulbgm.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import git.soulbgm.exception.JsonConvertException;

import java.util.List;
import java.util.Map;

/**
 * Json工具
 *
 * @author SoulBGM
 * @date 2024-02-27
 */
public class JsonTool {

    private static ObjectMapper objectMapper;

    private static ObjectMapper mapper() {
        if (objectMapper == null) {
            objectMapper = SpringBeanUtil.getBean(ObjectMapper.class);
        }
        return objectMapper;
    }

    /**
     * 将JSON字符串转换为对象
     *
     * @param json   json
     * @param tClass Class类
     * @return {@link T}
     */
    public static <T> T parse(String json, Class<T> tClass) {
        try {
            return mapper().readValue(json, tClass);
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

    /**
     * 作语法分析
     * 将JSON字符串转换为Map<String, Object>
     *
     * @param json json
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public static Map<String, Object> parse(String json) {
        try {
            return mapper().readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

    /**
     * 解析数组
     * 将JSON字符串转换为集合对象
     *
     * @param json   json
     * @param tClass Class类
     * @return {@link List}<{@link T}>
     */
    public static <T> List<T> parseArray(String json, Class<T> tClass) {
        try {
            return mapper().readValue(json, new TypeReference<List<T>>() {});
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

    /**
     * 解析数组
     * 将JSON字符串转换为List<Map<String, Object>>
     *
     * @param json json
     * @return {@link List}<{@link Map}<{@link String}, {@link Object}>>
     */
    public static List<Map<String, Object>> parseArray(String json) {
        try {
            return mapper().readValue(json, new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

    /**
     * 将对象转换为JSON字符串
     *
     * @param t 实体类
     * @return {@link String}
     */
    public static <T> String toJson(T t) {
        try {
            return mapper().writeValueAsString(t);
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

    /**
     * 将集合对象转换为JSONArray字符串
     *
     * @param list 列表
     * @return {@link String}
     */
    public static <T> String toJsonArray(List<T> list) {
        try {
            return mapper().writeValueAsString(list);
        } catch (Exception e) {
            throw new JsonConvertException(e);
        }
    }

}
